package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import static com.hmdp.entity.RedisConstants.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private IShopTypeService typeService;

    @Override
    public Result saveByType() {
        List<ShopType> res = new ArrayList<>();
        //0.Redis中获取所有的数据
        List<String> typeList = redisTemplate.opsForList().range(SHOP_TYPE, 0, -1);
        if (!CollectionUtils.isEmpty(typeList)) {
            //1.不为空则序列化为对象返回
            for(String t : typeList) {
                res.add(JSONUtil.toBean(t, ShopType.class));
            }
            return Result.ok(res);
        }
        //2.到这里说明Redis中没有获取到数据，查询数据库
        res= typeService.query().orderByAsc("sort").list();
        if (CollectionUtils.isEmpty(res)) {
            return Result.fail("数据库未查找到店铺类型数据");
        }
        //3. 遍历存入Redis
        for(ShopType type : res) {
            redisTemplate.opsForList().leftPush(SHOP_TYPE, JSONUtil.toJsonStr(type));
        }
        redisTemplate.expire(SHOP_TYPE,1L, TimeUnit.HOURS);
        return Result.ok(res);
    }
}
